<?php
namespace App;
use Model\MediaMod;
use Model\MediaPicMod;
use Model\MediaVideoMod;
use Model\RedMod;
use Pub\tool\Setting as SettingCache;
use Pub\wx\WxTpl;

defined('IN_IA') or exit('Access Denied');

class Media extends Action
{
    private $Media = null;
    private $MediaPic = null;
    private $MediaVideo = null;

    private $_type = 'image';  //素材类型
    public function __construct()
    {
        parent::__construct();
        $this->Media = new MediaMod();
        $this->getUid();
    }

    /**
     * 上传一个图片
     * @param array FILES['file']  文件
     */
    public function upload()
    {
        global $_W;
        set_time_limit(0);
        $_W['setting']['upload']['audio']['extentions'] = array("mp4","mov","rm","rmvb","wmv","avi","mpg","mpeg");
        load()->func('file');
        $this->_type = $this->_gpc['type'];
        $_video_thumb = false;  //视频封面
        $_remote_source = array();  //需要上传远程附件的列表
        if($this->_type == 'video'){
            $_video_thumb = $this->createVideoThumb($_FILES["thumb_file"]);
        }
        $_result = file_upload($_FILES['file'], $this->_type);
        //微擎方法执行失败
        if(!$_result['success']){
            $this->_result = array("status"=>"error","err_msg"=>$_result["message"]);
            $this->result($this->_result);
        }
        if($_result['success']){
            $_source = $_result['path'];
            $_thumb = false;
            if($this->_type == 'image') $_thumb = file_image_thumb(ATTACHMENT_ROOT.'/'.$_result['path'],'',1024);
            if($this->_w['setting']['remote']['type'] != 0){
                $_remote_source[] = $_source;
                if($this->_type == 'image'){
                    $_remote_source[] = $_thumb;
                }
            }
            $_data = array(
                'uniacid'=>$this->_uniacid,
                'uid'=>$this->_uid,
                'type'=>$this->_gpc['type'],
                'filename'=>$_FILES['file']['name'],
                'time'=>TIMESTAMP,
                'status'=>SettingCache::get(SettingCache::MEDIA_CHECK),
                'size'=>$_FILES['file']['size']
            );
            if($this->Media->insert($_data)){
                $_add_media = false;
                $_media_id = pdo_insertid();
                if($this->_type == 'image'){
                    $_add_media = $this->addMediaPic($_media_id,$_source,$_thumb);
                }else{
                    $_add_media = $this->addMediaVideo($_media_id,$_source,$_video_thumb);
                }
                if(!$_add_media){
                    $this->_result = array('status'=>'error','err_status'=>3,'err_msg'=>'媒体创建失败');
                }else{
                    //发送审核模板消息通知
                    if(SettingCache::get(SettingCache::MEDIA_CHECK) == 2 && SettingCache::get(SettingCache::ADMIN_UID)){
                        $this->sendCheckTplMessage($this->_type);
                    }
                    if($this->_type == 'image'){
                        $this->_result = array('status'=>'success','data'=>array('id'=>$_media_id,'type'=>$this->_type,'status'=>$_data['status'],'filename'=>$_data['filename'],'value'=>$_thumb,'url'=>tomedia($_thumb),'remote_source'=>$_remote_source));
                    }else{
                        $this->_result = array('status'=>'success','data'=>array('id'=>$_media_id,'type'=>$this->_type,'status'=>$_data['status'],'filename'=>$_data['filename'],'value'=>$_thumb,'video'=>tomedia($_source),'video_value'=>$_source,'url'=>tomedia($_video_thumb),'remote_source'=>$_remote_source));
                    }
                }
            }else{
                $this->_result = array('status'=>'error','err_status'=>2,'err_msg'=>'文件创建失败');
            }
        }else{
            $this->_result = array('status'=>'error','err_status'=>1,'err_msg'=>'上传文件失败');
        }
        $this->result($this->_result);
    }

    /**
     * 发送审核模板消息给管理员
     * @param string $_media_type 媒体类型
     */
    private function sendCheckTplMessage($_media_type)
    {
        $WxTpl = new WxTpl();
        $_fans = $this->uidToFans(SettingCache::get(SettingCache::ADMIN_UID));
        $_openid = KUYUAN_DEBUG ? 'oxYQT1DAyMPEFXMzjjJ-Rz1OQa-c' : $_fans['openid'];
        $_data = array(
            "first"=>array(
                "value"=>'【'.SettingCache::get(SettingCache::WEB_NAME)."】用户上传素材审核通知"
            ),
            "keyword1"=>array(
                "value"=>$_media_type == "image" ? "图片" : "视频"
            ),
            "keyword2"=>array(
                "value"=>date("Y-m-d H:i:s",TIMESTAMP)
            ),
            "remark"=>array(
                "value"=>"请尽快前往后台审核素材"
            )
        );
        $WxTpl->send(
            $_openid,
            SettingCache::get(SettingCache::MESSAGE_MEDIA_CHECK),
            $_data);
    }

    /**
     * 创建视频封面
     * @param array file 封面文件
     * @return string 封面地址
     */
    private function createVideoThumb($_file)
    {
        $_result = file_upload($_file,'image');
        //微擎方法执行失败
        if(!$_result['success']){
            $this->_result = array("status"=>"error","err_msg"=>$_result["message"]);
            $this->result($this->_result);
        }else{
            $_source = $_result['path'];
            if($this->_w['setting']['remote']['type'] != 0){
                file_remote_upload($_source);
            }
            return $_source;
        }
    }

    /**
     * 上传远程附件
     * @param array source 要上传的资源
     */
    public function uploadRemoteFile()
    {
        ignore_user_abort(true);
        set_time_limit(0);
        load()->func('file');
        foreach($this->_gpc["source"] as $_v){
            file_remote_upload($_v);
        }
    }

    /**
     * 新增图片素材
     * @param integer $_media_id  素材库id
     * @param string $_source 原图
     * @param string $_thumb 缩略图
     * @return mixed
     */
    private function addMediaPic($_media_id,$_source,$_thumb)
    {
        $this->MediaPic = new MediaPicMod();
        $_media_data = array(
            'media_id'=>$_media_id,
            'source'=>$_source,
            'thumb'=>$_thumb
        );
        return $this->MediaPic->insert($_media_data);
    }

    /**
     * 写入视频数据
     * @param $_media_id
     * @param $_source
     * @param $_thumb
     * @return mixed
     */
    private function addMediaVideo($_media_id,$_source,$_thumb)
    {
        $this->MediaVideo = new MediaVideoMod();
        $_media_data = array(
            'media_id'=>$_media_id,
            'source'=>$_source,
            'thumb'=>$_thumb
        );
        return $this->MediaVideo->insert($_media_data);
    }

    /**
     * 获取指定用户的素材库列表
     * @param type 请求类型  image 和 video
     * @param limit 请求下标数量
     */
    public function getList()
    {
        $_where = array('uniacid'=>$this->_uniacid,'uid'=>$this->_uid);
        if($this->_gpc["type"] != 'all'){
            $_where["type"] = $this->_gpc["type"];
        }
        $_list = $this->Media->findAll(
            $_where,
            array('order'=>array('id','desc'),'limit'=>$this->_gpc['limit']),
            array('id','filename','status','type')
        );
        if(count($_list) > 0){
            $this->MediaPic = new MediaPicMod();
            $this->MediaVideo = new MediaVideoMod();
            foreach($_list as $_k=>$_v){
                $_media = array();
                if($_v["type"] == 'image'){
                    $_media = $this->MediaPic->findOne(array('media_id'=>$_v['id']),array('thumb'));
                }else{
                    $_media = $this->MediaVideo->findOne(array('media_id'=>$_v['id']),array('thumb','source'));
                    $_list[$_k]['video_value'] = $_media['source'];
                    $_list[$_k]['video'] = tomedia($_media['source']);
                }
                $_list[$_k]['value'] = $_media['thumb'];
                $_list[$_k]['url'] = tomedia($_media['thumb']);
            }
            $this->_result = array('status'=>'success','data'=>$_list);
        }
        $this->result($this->_result);
    }

    /**
     * 获取用户当前的素材库内存
     */
    public function getUserMemory()
    {
        $_memory = $this->Media->sum(array('uniacid'=>$this->_uniacid,'uid'=>$this->_uid),'size');
        if($_memory){
            $_memory = $_memory / 1024 / 1024;
            $this->_result = array('status'=>'success','data'=>$_memory);
        }else{
            $this->_result = array('status'=>'success','data'=>0);
        }
        $this->result($this->_result);
    }

    /**
     * 删除素材
     * @param integer media_id  素材id
     * @param string type 素材类型
     */
    public function delete()
    {
        $MediaMedia = null;
        $_media = array();
        $MediaMedia = null;
        if($this->_gpc["type"] == 'video'){
            $MediaMedia = new MediaVideoMod();
        }else{
            $MediaMedia = new MediaPicMod();
        }
        $_media = $MediaMedia->findOne(array('media_id'=>$this->_gpc['media_id']),array('source','thumb'));
        $this->deleteCheck($this->_uid,$_media['thumb'],$_media['source']);
        if($this->Media->delete(array('id'=>$this->_gpc['media_id']))){
            if($MediaMedia->delete(array('media_id'=>$this->_gpc['media_id']))){
                load()->func('file');
                file_delete($_media['source']);
                file_delete($_media['thumb']);
                file_remote_delete($_media['source']);
                file_remote_delete($_media['thumb']);
                $this->_result = array('status'=>'success');
            }else{
                $this->_result = array('status'=>'error','err_status'=>2,'err_msg'=>'删除失败');
            }
        }else{
            $this->_result = array('status'=>'error','err_status'=>1,'err_msg'=>'删除失败');
        }
        $this->result($this->_result);
    }

    /**
     *删除素材验证
     * @param integer $_uid 当前用户id
     * @param string $_media_1 素材1
     * @param string $_media_2 素材2
     */
    private function deleteCheck($_uid,$_media_1,$_media_2 = '')
    {
        $Red = new RedMod();
        if($Red->testRedUseMedia($_media_1,$_uid,$this->_uniacid)){
            $this->_result = array('status'=>'error','err_status'=>3,'err_msg'=>'素材正在使用中禁止删除');
            $this->result($this->_result);
        }
        if($_media_2 != '' && $Red->testRedUseMedia($_media_2,$_uid,$this->_uniacid)){
            $this->_result = array('status'=>'error','err_status'=>3,'err_msg'=>'素材正在使用中禁止删除');
            $this->result($this->_result);
        }
    }

}